package com.example.demo.tool;/**
 * @Auter 李孝在
 * @Date 2025/1/18
 */

/**
 * @projectName: demo
 * @package: com.example.demo.tool
 * @className: FileDeleteTool
 * @author: Eric
 * @description: TODO
 * @date: 2025/1/18 22:22
 * @version: 1.0
 */
import com.example.demo.exception.AppException;
import com.example.demo.exception.AppExceptionCodeMsg;

import java.io.File;
import java.io.IOException;

public class FileDeleteTool {

    /**
     * 删除单个文件
     */
    private static void deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new AppException(AppExceptionCodeMsg.PATH_NOT_EXIST);
        }
        if (!file.delete())throw new AppException(AppExceptionCodeMsg.FILE_DELETE_FAILED);

    }

    /**
     * 删除文件夹及其内容
     */
    private static void deleteDirectory(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
          throw new AppException(AppExceptionCodeMsg.PATH_NOT_EXIST);
        }
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    deleteFile(file.getAbsolutePath());
                } else if (file.isDirectory()) {
                    deleteDirectory(file.getAbsolutePath());
                }
            }
        }
        if(!dir.delete()){
            throw new AppException(AppExceptionCodeMsg.DIR_DELETE_FAILED);
        }
    }

    /**
     * 删除文件或文件夹
     * @param path 文件或文件夹路径
     * @return 删除成功返回true，否则返回false
     */
    public static void delete(String path) {
        File file = new File(path);
        if (file.exists()) {
            if (file.isFile()) {
                 deleteFile(path);
            } else if (file.isDirectory()) {
                 deleteDirectory(path);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.PATH_NOT_EXIST);
        }

    }
}
